package com.example.module.user.login.repository

import android.util.Log
import com.example.common.database.entity.DBUser
import com.example.common.database.impl.UserDaoImpl
import com.example.common.sdk.http.WanAndroidRemote
import com.example.common.sdk.http.flowWrapObject
import com.example.common.sdk.entity.UIResult
import com.example.library.datasource.CacheDataSource
import com.example.library.datasource.ParameterCollector
import com.example.module.user.login.entity.UserEntity
import kotlinx.coroutines.flow.Flow


class LoginRepository : ILoginApi {
    companion object {
        private const val TAG = "LoginRepository"
        private const val CACHE_USERNAME = "cache_username"
        private const val CACHE_PASSWORD = "cache_password"
    }

    private val remoteDataSource = WanAndroidRemote
    private val userDao = UserDaoImpl()
    private val cacheDataSource = CacheDataSource
    override suspend fun login(userName: String, password: String): Flow<UIResult<UserEntity>> {
        val parameterCollector = ParameterCollector.Builder<UserEntity>()
            .setRequestType(ParameterCollector.RequestType.PostForm)
            .setResultType(ParameterCollector.ResultType.Object)
            .putParams("username", userName)
            .putParams("password", password)
            .setClazz(UserEntity::class.java)
            .build("user/login")
        return flowWrapObject {
            //网络请求
            val uiResult = remoteDataSource.requestObject(parameterCollector)
            if (uiResult.status == UIResult.Status.Success) {
                val userEntity = uiResult.data
                //数据库存储
                userEntity?.let {
                    val dbUser = DBUser(it.id, it.name)
                    userDao.add(dbUser)
                    Log.d(TAG, "保存到数据库成功")
                    val user = userDao.getOne(it.id)
                    Log.d(TAG, "数据库里的用户信息：${user}")
                }
                // KV 缓存
                cacheDataSource.putString(CACHE_USERNAME, userName)
                cacheDataSource.putString(CACHE_PASSWORD, password)

            }
            return@flowWrapObject uiResult
        }
    }

    override fun getCacheUserName(): String {
        return cacheDataSource.getString(CACHE_USERNAME)
    }

    override fun getCachePassword(): String {
        return cacheDataSource.getString(CACHE_PASSWORD)
    }

}